package com.tencent.map;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import java.net.URLDecoder;
import java.util.Map;

import me.gfuil.bmap.uri.sdk.BmapHelper;
import me.gfuil.bmap.uri.sdk.Poi;
import me.gfuil.bmap.uri.sdk.StringUtils;

public class QuickUriActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView text = findViewById(R.id.text);

    if (null != getIntent().getDataString()) {
      text.setText(getIntent().getDataString());

      navi();
    }

    text.setOnClickListener(v -> copy());
    findViewById(R.id.btn_feedback).setOnClickListener(v -> feedback());
    findViewById(R.id.btn_navi).setOnClickListener(v -> navi());

  }

  @Override
  protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    if (null != intent){
      TextView text = findViewById(R.id.text);
      text.setText(intent.getDataString());
      setIntent(intent);

      navi();
    }
  }

  public void navi() {
    try {
      String dataUri = URLDecoder.decode(getIntent().getDataString());
      if (StringUtils.isEmpty(dataUri)) {
        Toast.makeText(this, "未找到位置信息", Toast.LENGTH_SHORT).show();
        return;
      }

      Log.i("bmap_", "navi: " + dataUri);

      Map<String, String> map = StringUtils.getUrlRequest(dataUri);

      if (null == map || map.isEmpty()) {
        Toast.makeText(this, "未找到位置信息", Toast.LENGTH_SHORT).show();
        return;
      }

      if (dataUri.startsWith("qqmap://map")) {
        String latlng = null, address = null;

        if (dataUri.contains("map/search")) {
          latlng = map.get("center");
          address = map.get("keyword");
        } else if (dataUri.contains("map/nearby")) {
          latlng = map.get("coord");
          address = map.get("placeName");
        } else if (dataUri.contains("map/marker")) {

          String[] params = StringUtils.convertStrToArray(map.get("marker"), "[;]");
          if (null != params){
            for (String p : params) {
              if (p.startsWith("coord:")) {
                latlng = p.substring(6);
              } else if (p.startsWith("title:")) {
                address = p.substring(6);
              }
            }

          }

        } else if (dataUri.contains("map/routeplan")) {

          String[] fromCoord = StringUtils.convertStrToArray(map.get("fromcoord"), "[,]");
          String[] toCoord = StringUtils.convertStrToArray(map.get("tocoord"), "[,]");

          Poi start = null, end = null;
          if (null != fromCoord && fromCoord.length >= 2) {
            start = new Poi();
            start.setLatitude(StringUtils.getStringNumberDouble(fromCoord[0]));
            start.setLongitude(StringUtils.getStringNumberDouble(fromCoord[1]));
            if (null != map.get("from")) {
              start.setName(map.get("from"));
            } else {
              start.setName("出发点");
            }

          }
          if (null != toCoord) {
            end = new Poi();
            end.setLatitude(StringUtils.getStringNumberDouble(toCoord[0]));
            end.setLongitude(StringUtils.getStringNumberDouble(toCoord[1]));
            end.setName(map.get("to"));
            if (null != map.get("to")) {
              end.setName(map.get("to"));
            } else {
              end.setName("目的点");
            }
          }

          String type = map.get("type");
          if (StringUtils.isEmpty(type)){
            type = map.get("qqmap://map/routeplan/type");
          }
          int typeRoute = BmapHelper.TYPE_ROUTE_DEFAULT;
          if ("drive".equals(type)){
            typeRoute = BmapHelper.TYPE_ROUTE_DRIVE;
          } else if ("bus".equals(type)){
            typeRoute = BmapHelper.TYPE_ROUTE_BUS;
          } else if ("walk".equals(type)){
            typeRoute = BmapHelper.TYPE_ROUTE_WALK;
          } else if ("bike".equals(type)){
            typeRoute = BmapHelper.TYPE_ROUTE_BIKE;
          }

          BmapHelper.route(this, BmapHelper.TYPE_MAP_DEFAULT, typeRoute, start, end);

          return;
        }

        if (StringUtils.isEmpty(latlng) || !latlng.contains(",")) {
          latlng = "0,0";

          String geo = "geo:" + latlng + "?q=" + address;

          Uri uri = Uri.parse(geo);
          Intent intent = new Intent(Intent.ACTION_VIEW, uri);
          intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          startActivity(intent);
          return;
        }

        if (StringUtils.isEmpty(address)) {
          address = "外部传来的位置";
        }

        Poi poi = new Poi();
        String[] latlngStrs = StringUtils.convertStrToArray(latlng, "[,]");

        poi.setName(address);
        poi.setLatitude(StringUtils.getStringNumberDouble(latlngStrs[0]));
        poi.setLongitude(StringUtils.getStringNumberDouble(latlngStrs[1]));
        BmapHelper.marker(this, poi);


      } else {
        Toast.makeText(this, "暂不支持的链接", Toast.LENGTH_SHORT).show();
      }

      new Handler(Looper.getMainLooper()).postDelayed(this::finish, 1000);
    } catch (Exception e) {
      e.printStackTrace();
      Toast.makeText(this, "错误：" + e.getMessage(), Toast.LENGTH_SHORT).show();
    }
  }

  public void copy() {
    if (!StringUtils.isEmpty(getIntent().getDataString())) {
      ClipboardManager myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
      myClipboard.setPrimaryClip(ClipData.newPlainText("text", getIntent().getDataString()));
      Toast.makeText(QuickUriActivity.this, "链接已复制", Toast.LENGTH_SHORT).show();
    } else {
      Toast.makeText(QuickUriActivity.this, "无链接可复制", Toast.LENGTH_SHORT).show();
    }
  }

  public void feedback() {
    try {
      copy();
      Uri uri = Uri.parse(getString(R.string.link_feedback));
      Intent intent = new Intent(Intent.ACTION_VIEW, uri);
      startActivity(intent);
    } catch (Exception e) {
      e.printStackTrace();
      Toast.makeText(this, "错误：" + e.getMessage(), Toast.LENGTH_SHORT).show();
    }
  }
}
